<template>
  <el-dialog v-model="visible" title="登录" width="400px" @close="handleClose">
    <el-tabs v-model="activeTab">
      <!-- 登录 tab -->
      <el-tab-pane label="登录" name="login">
        <el-form :model="loginForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" />
          </el-form-item>
          <!-- 新增验证码部分 -->
          <el-form-item label="验证码" prop="code">
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-input
                  v-model="loginForm.code"
                  maxlength="4"
                  placeholder="请输入验证码"
                  style="width: 120px;"
                  @keyup.enter="handleLogin"
              />
              <div style="cursor: pointer; display: flex; align-items: center;" @click="refreshCaptcha">
                <img
                    v-if="captchaImage"
                    :src="captchaImage"
                    alt="验证码"
                    style="height: 40px; border: 1px solid #dcdfe6; border-radius: 4px;"
                    @error="handleImageError"
                />
                <div v-else
                     style="width: 120px; height: 40px; border: 1px solid #dcdfe6; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #999;">
                  加载中...
                </div>
              </div>
              <el-button
                  :loading="captchaLoading"
                  style="padding: 0; margin-left: 5px;"
                  type="text"
                  @click="refreshCaptcha"
              >
                刷新
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loginLoading" type="primary" @click="handleLogin">登录</el-button>
            <el-button @click="activeTab = 'register'">注册</el-button>
            <el-button @click="activeTab = 'reset'">重置密码</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 注册 tab -->
      <el-tab-pane label="注册" name="register">
        <el-form :model="registerForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名(4-16)"
                      @input="checkUsernameFormat"
            />
            <div style="margin-top: 4px; font-size: 12px; color: #999;">
              4-16位，支持字母、数字、下划线（_）、短横线（-）
            </div>
            <div v-if="usernameError" style="margin-top: 4px; font-size: 12px; color: #f56c6c;">
              {{ usernameError }}
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="registerForm.code" placeholder="请输入验证码" style="width: 200px;" />
            <el-button :disabled="registerCodeCountdown > 0" @click="getCode">
              {{ registerCodeCountdown > 0 ? `${registerCodeCountdown}秒后重试` : '获取验证码' }}
            </el-button>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" placeholder="请输入密码(数字+英文)" type="password"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRegister">注册</el-button>
            <el-button @click="activeTab = 'login'">登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 重置密码 tab -->
      <el-tab-pane label="重置密码" name="reset">
        <el-form :model="resetForm" label-width="80px">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="resetForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="resetForm.code" placeholder="请输入验证码" style="width: 200px;" />
            <el-button :disabled="resetCodeCountdown > 0" @click="getResetCode">
              {{ resetCodeCountdown > 0 ? `${resetCodeCountdown}秒后重试` : '获取验证码' }}
            </el-button>
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input v-model="resetForm.password" placeholder="请输入新密码(数字+字母)" type="password"/>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="resetForm.confirmPassword" placeholder="请确认新密码(数字+字母)" type="password"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleReset">重置密码</el-button>
            <el-button @click="activeTab = 'login'">返回登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>
<script setup>
import {reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import http from "@/request/http.js";
import {useUserStore} from "@/stores/userStore.js";

const visible = ref(false)
const activeTab = ref('login')
const registerCodeCountdown = ref(0)
const resetCodeCountdown = ref(0)
const captchaImage = ref('') // 验证码图片URL
const captchaLoading = ref(false) // 验证码加载状态
const loginLoading = ref(false) // 登录加载状态

const usernameError = ref('');
const userStore = useUserStore();

// 监听模态框显示，自动刷新验证码
watch(visible, (newVal) => {
  if (newVal && activeTab.value === 'login') {
    refreshCaptcha()
  }
})

// 监听tab切换，切换到登录tab时刷新验证码
watch(activeTab, (newVal) => {
  if (newVal === 'login') {
    refreshCaptcha()
  }
})

const checkUsernameFormat = () => {
  const usernameRegex = /^[a-zA-Z0-9_-]{4,16}$/;
  if (!registerForm.username) {
    usernameError.value = '';
    return;
  }
  if (!usernameRegex.test(registerForm.username)) {
    usernameError.value = '用户名格式不正确：需4-16位，仅支持字母、数字、_、-';
  } else {
    usernameError.value = '';
  }
};

const loginForm = reactive({username: '', password: '', code: ''})
const registerForm = reactive({username: '', email: '', code: '', password: ''})
const resetForm = reactive({email: '', code: '', password: '', confirmPassword: ''})

// // 刷新验证码 - 修复版本
// const refreshCaptcha = async () => {
//   captchaLoading.value = true;
//   try {
//     // 使用完整的URL，因为axios配置了baseURL，但img标签不会走axios拦截器
//     const timestamp = new Date().getTime();
//     // 直接使用完整后端URL，避免代理问题
//     captchaImage.value = await http.get(`/api/captcha/arithmetic?t=${timestamp}`);
//
//     // 测试图片是否能正常加载
//     await new Promise((resolve, reject) => {
//       const img = new Image();
//       img.onload = resolve;
//       img.onerror = reject;
//       img.src = captchaImage.value;
//     });
//
//   } catch (error) {
//     console.error('验证码加载失败：', error);
//     ElMessage.error('验证码加载失败，请点击刷新');
//     // 如果直接URL失败，尝试通过axios获取blob
//     await getCaptchaAsBlob();
//   } finally {
//     captchaLoading.value = false;
//   }
// }

// 备选方案：通过axios获取验证码图片
const refreshCaptcha = async () => {
  try {
    const response = await http.get('/api/captcha/arithmetic', {
      responseType: 'blob',
      params: {t: new Date().getTime()}
    });

    // 创建blob URL
    const blob = new Blob([response], {type: 'image/png'});
    captchaImage.value = URL.createObjectURL(blob);
  } catch (error) {
    console.error('通过blob获取验证码失败：', error);
    ElMessage.error('验证码获取失败');
  }
}

// 处理图片加载错误
const handleImageError = () => {
  ElMessage.error('验证码加载失败，请点击刷新');
  captchaImage.value = '';
}

// 修改登录逻辑，添加验证码验证
const handleLogin = async () => {
  if (!loginForm.username) {
    ElMessage.error('请输入用户名');
    return;
  }
  if (!loginForm.password) {
    ElMessage.error('请输入密码');
    return;
  }
  if (!loginForm.code) {
    ElMessage.error('请输入验证码');
    return;
  }

  loginLoading.value = true;
  try {
    const isSuccess = await userStore.login(loginForm.username, loginForm.password, loginForm.code);
    if (isSuccess) {
      ElMessage.success('登录成功');
      visible.value = false;
      // 登录成功后清空表单
      Object.assign(loginForm, {username: '', password: '', code: ''})
    } else {
      // 登录失败时刷新验证码
      loginForm.code = ''; // 清空验证码输入框
    }
  } catch (error) {
    // 登录失败时刷新验证码
    loginForm.code = ''; // 清空验证码输入框
    ElMessage.error(error.response?.data?.message || '登录失败，请检查用户名、密码或验证码');
  } finally {
    loginLoading.value = false;
  }
};

const handleRegister = async () => {
  if (registerForm.password.length < 6) {
    ElMessage.error('密码长度至少6位');
    return;
  }

  try {
    // 先检查用户名格式
    const usernameRegex = /^[a-zA-Z0-9_-]{4,16}$/;
    if (!usernameRegex.test(registerForm.username)) {
      ElMessage.error('用户名格式不正确：需4-16位，仅支持字母、数字、_、-');
      return;
    }

    // 检查邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(registerForm.email)) {
      ElMessage.error('邮箱格式不正确');
      return;
    }

    if (!registerForm.code) {
      ElMessage.error('请输入验证码');
      return;
    }

    console.log('发送注册请求:', {
      username: registerForm.username,
      email: registerForm.email,
      verificationCode: registerForm.code,
      password: registerForm.password,
    });

    // 发送注册请求
    const response = await http.post('/admin/user/registerUser', {
      username: registerForm.username,
      email: registerForm.email,
      verificationCode: registerForm.code,
      password: registerForm.password,
    });

    console.log('注册响应:', response);

    // 根据后端返回格式调整
    if (response.code === 0 || response.success) {
      // 注册成功后尝试登录
      const isSuccess = await userStore.login(registerForm.username, registerForm.password);
      if (isSuccess) {
        ElMessage.success('注册并登录成功');
        visible.value = false;
        // 清空注册表单
        Object.assign(registerForm, {username: '', email: '', code: '', password: ''});
      } else {
        ElMessage.success('注册成功，请登录');
        activeTab.value = 'login';
      }
    } else {
      // 显示后端返回的具体错误信息
      ElMessage.error(response.message || '注册失败');
    }

  } catch (error) {
    console.error('注册失败详情:', {
      error: error,
      response: error.response,
      data: error.response?.data,
      status: error.response?.status
    });

    // 根据不同的错误状态码显示不同的提示信息
    if (error.response?.status === 400) {
      ElMessage.error(error.response?.data?.message || '请求参数错误');
    } else if (error.response?.status === 409) {
      ElMessage.error(error.response?.data?.message || '用户名或邮箱已存在');
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请稍后重试');
    } else {
      ElMessage.error(error.response?.data?.message || '注册失败，请重试');
    }
  }
};

const handleReset = async () => {
  if (!resetForm.email) {
    ElMessage.error('请输入邮箱');
    return;
  }
  if (!resetForm.code) {
    ElMessage.error('请输入验证码');
    return;
  }
  if (!resetForm.password) {
    ElMessage.error('请输入新密码');
    return;
  }
  if (!resetForm.confirmPassword) {
    ElMessage.error('请确认新密码');
    return;
  }
  if (resetForm.password !== resetForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  if (resetForm.password.length < 6) {
    ElMessage.error('密码长度至少6位')
    return
  }

  try {
    console.log('重置密码请求体:', {
      email: resetForm.email,
      verificationCode: resetForm.code,
      newPassword: resetForm.password,
      repeatPassword: resetForm.confirmPassword
    });

    // 直接使用请求体，不修改headers
    const res = await http.patch('/admin/user/resetUserPassword', {
      email: resetForm.email,
      verificationCode: resetForm.code,
      newPassword: resetForm.password,
      repeatPassword: resetForm.confirmPassword
    });

    console.log('重置密码响应:', res);

    // 根据后端返回格式处理
    if (res.code === 0) {
      ElMessage.success('密码重置成功,请重新登录');
      resetForm.email = '';
      resetForm.code = '';
      resetForm.password = '';
      resetForm.confirmPassword = '';
      visible.value = false;
      activeTab.value = 'login';
    } else {
      ElMessage.error(res.message || '密码重置失败');
    }

  } catch (error) {
    console.error('重置密码失败详情:', {
      error: error,
      response: error.response,
      data: error.response?.data,
      status: error.response?.status
    });

    // 如果是401错误，可能是会话问题，尝试清除会话
    if (error.response?.status === 401) {
      try {
        console.log('清除会话后重试');
        // 清除可能的会话问题
        sessionStorage.removeItem('token');
        localStorage.removeItem('token');

        // 重新发送请求
        const res2 = await http.patch('/admin/user/resetUserPassword', {
          email: resetForm.email,
          verificationCode: resetForm.code,
          newPassword: resetForm.password,
          repeatPassword: resetForm.confirmPassword
        });

        if (res2.code === 0) {
          ElMessage.success('密码重置成功,请重新登录');
          resetForm.email = '';
          resetForm.code = '';
          resetForm.password = '';
          resetForm.confirmPassword = '';
          visible.value = false;
          activeTab.value = 'login';
        } else {
          ElMessage.error(res2.message || '密码重置失败');
        }
        return;
      } catch (error2) {
        console.error('重试也失败:', error2);
      }
    }

    // 如果PATCH方法失败，尝试POST方法
    if (error.response?.status === 405) {
      try {
        console.log('尝试使用POST方法');
        const res3 = await http.post('/admin/user/resetUserPassword', {
          email: resetForm.email,
          verificationCode: resetForm.code,
          newPassword: resetForm.password,
          repeatPassword: resetForm.confirmPassword
        });

        if (res3.code === 0) {
          ElMessage.success('密码重置成功,请重新登录');
          resetForm.email = '';
          resetForm.code = '';
          resetForm.password = '';
          resetForm.confirmPassword = '';
          visible.value = false;
          activeTab.value = 'login';
        } else {
          ElMessage.error(res3.message || '密码重置失败');
        }
        return;
      } catch (error3) {
        console.error('POST方法也失败:', error3);
      }
    }

    // 显示具体的错误信息
    const errorMsg = error.response?.data?.message ||
        (error.response?.status === 401 ? '请先退出登录后再尝试重置密码' : '重置密码失败，请重试');
    ElMessage.error(errorMsg);
  }
}

const getCode = async () => {
  if (!registerForm.email) {
    ElMessage.error('请输入邮箱')
    return
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(registerForm.email)) {
    ElMessage.error('邮箱格式不正确')
    return
  }

  try {
    await http.post(
        `/api/captcha/emailCode?email=${encodeURIComponent(registerForm.email)}`,
        {},
        {
          headers: {'Content-Type': 'text/plain'}
        }
    )
    ElMessage.success('验证码发送成功')
    startCountdown('register')
  } catch (error) {
    console.error('验证码发送失败：', {
      status: error.response?.status,
      data: error.response?.data,
      config: error.response?.config
    })
    ElMessage.error(error.response?.data?.message || '验证码发送失败，请重试')
  }
}

const getResetCode = async () => {
  if (!resetForm.email) {
    ElMessage.error('请输入邮箱')
    return
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(resetForm.email)) {
    ElMessage.error('邮箱格式不正确')
    return
  }

  try {
    console.log('发送重置密码验证码，邮箱:', resetForm.email);

    // 方案1：直接在URL中拼接参数
    await http.get(`/admin/user/sendVerificationCode?email=${encodeURIComponent(resetForm.email)}`)

    ElMessage.success('验证码发送成功')
    startCountdown('reset')
  } catch (error) {
    console.error('重置验证码发送失败详情:', {
      error: error,
      response: error.response,
      data: error.response?.data,
      status: error.response?.status
    });

    // 如果方案1失败，尝试方案2
    if (error.response?.status === 400) {
      try {
        // 方案2：使用POST方法
        await http.post(`/admin/user/sendVerificationCode?email=${encodeURIComponent(resetForm.email)}`)
        ElMessage.success('验证码发送成功')
        startCountdown('reset')
        return;
      } catch (error2) {
        console.error('方案2也失败:', error2);
      }
    }

    ElMessage.error(error.response?.data?.message || '验证码发送失败，请重试')
  }
}

const startCountdown = (type) => {
  if (type === 'register') {
    registerCodeCountdown.value = 60
    const timer = setInterval(() => {
      registerCodeCountdown.value--
      if (registerCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } else {
    resetCodeCountdown.value = 60
    const timer = setInterval(() => {
      resetCodeCountdown.value--
      if (resetCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }
}

const handleClose = () => {
  visible.value = false
  Object.assign(loginForm, {username: '', password: '', code: ''})
  Object.assign(registerForm, {username: '', email: '', code: '', password: ''})
  Object.assign(resetForm, {email: '', code: '', password: '', confirmPassword: ''})
  activeTab.value = 'login'
}

window.addEventListener('showLoginModal', () => {
  visible.value = true
})
</script>